/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef UGAME_NET_TCPRUNNABLE_H_
#define UGAME_NET_TCPRUNNABLE_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <UGame/Macros.h>
#include <UGame/Base/AtomicValue.h>
#include <UGame/System/Runnable.h>
#include <UGame/System/Thread.h>
#include <UGame/System/Event.h>

struct event_base;
struct event;

namespace UGame {
namespace Net {

    class TcpRunnable : public System::Runnable
    {
    public:
        TcpRunnable(void);
        virtual ~TcpRunnable(void);

        bool Start(void);
        void Stop(void);
        void Join(void);

        struct event_base* AcquireBase(void) {
            ++_load;
            return _base;
        }
        void ReleaseBase(void) { --_load; }
        std::uint32_t GetLoad(void) const { return _load; }

        virtual void Run(void);

    private:
        void _Uninitialize(void);
        static void _OnTimeout(int, short, void *);

        struct event_base *_base;
        struct event *_dummyEvent;
        AtomicValue_UInt32 _load;
        System::Thread _thread;
        System::Event _startEvent;
        volatile bool _running;
        DISALLOW_COPY_AND_ASSIGN(TcpRunnable);
    };

}}

#endif // UGAME_NET_TCPRUNNABLE_H_
